<template>
  <FIModel v-model="visible" title="成员设置" @close="closeClick" @confirm="saveFunc">
    <el-row :gutter="20">
      <el-col :span="8">
        <FIFormItem prop="groupEname" label="用户组编码">
          <span>{{ editData.groupEname }}</span>
        </FIFormItem>
      </el-col>
      <el-col :span="8">
        <FIFormItem prop="groupCname" label="用户组名称">
          <span>{{ editData.groupCname }}</span>
        </FIFormItem>
      </el-col>
    </el-row>

    <FITable
      ref="tableRef"
      class="box-radius2"
      title="用户组用户列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="dataList"
      primaryKey="formId"
      insertable
      deletable
      delete-id="deleteGroupUsers"
      v-model:columns="columns"
      :showSaveModel="false"
      :isLoading="isTableLoading"
      :settingConfig="settingConfig"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-delete="deleteRow"
      @on-cell-select="selectClick"
    >
      <template #headerBtn>
        <FIButton id="saveGroupUsers" border @click="handleSave">保存</FIButton>
      </template>
    </FITable>
    <template #footer>
      <slot name="footer">
        <div class="dialog-footer">
          <FIButton @click="visible = false">关闭</FIButton>
        </div>
      </slot>
    </template>
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, ref, computed, watch } from 'vue'
import FIFormItem from '@/components/FIFormItem.vue'

import FIModel from '@/components/FIModel.vue'
import { apiGetUsersByGroupNo, apiSaveGroupUsers } from '@/api/user'
import { initSearchData } from '@/utils/common'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { getCurrentInstance } from 'vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { useRoute } from 'vue-router'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
const route = useRoute()
const emits = defineEmits(['close', 'update:setShow'])
const props = defineProps({
  // 圆角大小
  setShow: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const state = reactive({
  query: {
    groupEname: '',
    groupCname: '',
    current: 1,
    size: 10,
  },
})
const dataList = ref([])
const tableRef = ref(null)
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const isTableLoading = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 页面编码
const tableId = 'usersMemberSet'

const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  {
    label: '登录账号',
    prop: 'loginName',
    align: 'center',
    editable: true,
    editType: 'autoSelect',
    editConfig: {
      otherBinds: {
        apiUrl: '/rm2/userMaint/query',
        props: { value: 'loginName', label: 'loginName' },
        displayKey: ['loginName', 'userName'],
        searchParam: 'userAName',
      },
    },
  },
  {
    label: '用户姓名',
    prop: 'userName',
    align: 'center',
    queryName: '',
    editType: 'input',
    editable: false,
    filterable: true,
    sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    readonly: true,
  },
])
const selectClick = (scope, item) => {
  if (scope.column.property == 'loginName') {
    tableRef.value.setCellValue(scope.$index, 'userName', item.userName)
    tableRef.value.setCellValue(scope.$index, 'userId', item.userId)
  }
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}

const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.userId) {
        ids.push({
          userId: item.userId,
          groupId: props.editData.groupId,
        })
      }
    })
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('deleteGroupUsers', route.name)
  apiRequestPost(apiUrl, ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }

      // emits('update:setShow', false)
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
let visible: any = computed({
  get() {
    console.log('childSelectedValue', props.setShow)
    return props.setShow
  },
  set(val) {
    emits('update:setShow', val)
  },
})
// const addRowSave = (data) => {
//   handleSave(data, 'add')
// }
const handleSave = () => {
  let ids = []
  let obj = {}
  console.log(checkedRows.value, 'checkedRows.value')
  for (let i of checkedRows.value) {
    if (i.loginName == '') {
      useMessage().warning('请选择登录账号')
      return
    }

    obj = {
      groupId: props.editData.groupId,
      userId: i.userId,
    }

    ids.push(obj)
  }
  isTableLoading.value = true
  saveSuccessful.value = false
  if (!ids.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  apiSaveGroupUsers(ids)
    .then((res) => {
      console.log(res, 'res678')
      if (res.data.success) {
        useMessage().success(res.data.message)
        isTableLoading.value = false
        searchFn()
        // emits('update:setShow', false)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      useMessage().error(error.data.message)
    })
}
const searchFn = (type?: string, columnsVal?: any, orgId?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const par = {
    groupNo: props.editData.groupEname || '',
    ...state.query,
  }
  apiGetUsersByGroupNo(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        dataList.value = res.data.data
        // pageConfig.pageSize = 50
        pageConfig.total = res.data.data.length
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
      console.log('apiRequestPost---error', error)
    })
}
const closeClick = () => {
  emits('update:setShow', false)
}

const saveFunc = () => {
  emits('update:setShow', false)
  // console.log(props.editData.groupId,'checkedRows')
  // let ids = []
  // Array.isArray(checkedRows.value) &&
  //   checkedRows.value.forEach((item: any) => {
  //     if (item?.userId) {
  //       ids.push({
  //         groupId:props.editData.groupId,
  //         userId:item.userId
  //       })
  //     }
  //   })
  //   console.log(ids,'ids')
}
watch(
  () => props.setShow,
  () => {
    searchFn()
  }
)
</script>
<style lang="less" scoped></style>
